import dayjs from "dayjs";
// 千分位
/**
 *
 * @param number 数字
 * @param count 百 / 千 / 万
 * @returns
 */
export const formatNumber = (number: number, count = 4) => {
  return (number / Math.pow(10, count)).toFixed(1);
};

/**
 * 获取作者
 * @param arr
 * @returns
 */
export const getAuth = (arr: any[] = []) => {
  return arr
    .reduce((pre, cur) => {
      pre = pre + " / " + cur.name;
      return pre;
    }, "")
    .substring(2);
};

/**
 * 少两位补 0
 * @param str
 * @returns
 */
export const addZero = (str: string) => str.padStart(2, "0");

/**
 * 格式化时间
 */
export const formatDate = (pattern = "YYYY-MM-DD", time?: string | Date) => {
  return dayjs(time).format(pattern);
};

/**
 * 防抖函数
 */
export function debounce(fn: Function, delay = 300) {
  let timer: number;
  return function (...args: any[]) {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

/**
 * 去重
 */
export function uniq(list: any[], key: string) {
  const obj: Record<string, any> = {};
  const result = [];
  for (let i = 0; i < list.length; i++) {
    const item = list[i];
    if (!obj[item[key]]) {
      result.push(item);
      obj[item[key]] = true;
    }
  }
  return result;
}
